﻿using System;
using System.Collections;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using com.kmxy.Common;

namespace com.kmxy.MonitorModel
{
    /// <summary>
    /// 服务控制与管理器
    /// </summary>
    public class WinServiceManager
    {
        private readonly GlobalToolkit _tools = GlobalToolkit.GetInstance();
        /// <summary>
        /// 服务名称 
        /// </summary>
        public string ServiceName { get; private set; }

        public WinServiceManager(string serviceName)
        {
            ServiceName = serviceName;
        }

        #region Windows服务控制区

        #region 安装服务
        /// <summary>
        /// 安装服务
        /// </summary>
        /// <param name="stateSaver"></param>
        /// <param name="filePath"></param>
        public void InstallService(IDictionary stateSaver, string filePath, string fileName, bool isStart = false)
        {
            try
            {
                

                var service = new ServiceController(ServiceName);
                if (!ServiceIsExisted(ServiceName))
                {
                    var myString = new string[1];
                    myString[0] = $"/logFile={ServiceName}-Install.log";
                    var transactedInstaller = new TransactedInstaller();
                    //Install Service  
                    var myAssemblyInstaller = new AssemblyInstaller
                    {
                        UseNewContext = true,
                        Path = $"{filePath}{fileName}",
                        CommandLine = myString
                    };
                    transactedInstaller.Installers.Add(myAssemblyInstaller);
                    transactedInstaller.Install(stateSaver);
                    //--Start Service  
                    if (isStart)
                    {                        
                        service.Start();
                    }
                }
                else
                {
                    if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
                    {
                        service.Start();
                    }
                }
            }
            catch (Exception e)
            {
                _tools.Logs(GetType(), e, "InstallService()", LogType.Error);
            }
        }
        #endregion

        #region 卸载windows服务
        /// <summary>
        /// 卸载windows服务
        /// </summary>
        /// <param name="filepath"></param>
        public void UnInstallService(string filepath, string fileName)
        {
            try
            {
                if (ServiceIsExisted(ServiceName))
                {
                    var myString = new string[1];
                    myString[0] = $"/logFile={ServiceName}-UnInstall.log";
                    var transactedInstaller = new TransactedInstaller();
                    var myAssemblyInstaller = new AssemblyInstaller
                    {
                        UseNewContext = true,
                        Path = filepath + fileName,
                        CommandLine = myString
                    };
                    transactedInstaller.Installers.Add(myAssemblyInstaller);
                    transactedInstaller.Uninstall(null);

                }
            }
            catch (Exception e)
            {
                _tools.Logs(GetType(), e, "UnInstallService()", LogType.Error);
            }
        }
        #endregion

        #region 判断window服务是否存在
        /// <summary>
        /// 判断window服务是否存在
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public bool ServiceIsExisted(string serviceName)
        {
            var services = ServiceController.GetServices();
            serviceName = serviceName.ToLower();
            var x = from l in services where l.ServiceName.ToLower() == serviceName select l;
            if (x.Any())
                return true;
            else
                return false;
            //foreach (ServiceController s in services)
            //{
            //    if (s.ServiceName == serviceName)
            //    {
            //        return true;
            //    }
            //}
            //return false;
        }
        #endregion

        #region 判断window服务是否启动
        /// <summary>  
        /// 判断某个Windows服务是否启动  
        /// </summary>  
        /// <returns></returns>  
        public static bool IsServiceStart(string serviceName)
        {
            var psc = new ServiceController(serviceName);
            var bStartStatus = false;
            try
            {
                if (!psc.Status.Equals(ServiceControllerStatus.Stopped))
                {
                    bStartStatus = true;
                }

                return bStartStatus;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion

        #region 启动服务
        public string GetService(string serviceName)
        {
            var serviceState = string.Empty;
            if (ServiceIsExisted(serviceName))
            {
                using (var service = new ServiceController(serviceName))
                {
                    if (service != null)
                        serviceState = service.Status.ToString();
                }
                return serviceState;
            }
            else
            {
                return "NoExists";
            }
            return "Unknowd";
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public bool StartService(string serviceName)
        {
            var flag = true;
            if (ServiceIsExisted(serviceName))
            {
                var service = new ServiceController(serviceName);
                if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending)
                {
                    service.Start();
                    for (var i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == ServiceControllerStatus.Running)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            flag = false;
                        }
                    }
                }
            }
            return flag;
        }
        #endregion

        #region 停止服务

        public bool StopService(string serviceName)
        {
            var flag = true;
            if (ServiceIsExisted(serviceName))
            {
                var service = new ServiceController(serviceName);
                if (service.Status == ServiceControllerStatus.Running)
                {
                    service.Stop();
                    for (var i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == ServiceControllerStatus.Stopped)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            flag = false;
                        }
                    }
                }
            }
            return flag;
        }
        #endregion

        #endregion
    }
}
